import { ApprovalComplete } from '../Complete';
import { ApprovalCommentForm } from '../Comment';
import { approvalRefreshEventName, useApprovalProvide } from '@/components/business/Approval/approval-helper';
import { useRevoke } from '@/components/business/Approval/approval-helper/useRevoke';
import { MciButton, MciDialog, MciNotification } from '@/components/base';
import * as i18n from '@/locales';
import { createFormV2, IVitalFormV2Ctx, VitalFormV2 } from 'vital';
import { IPostWorkflowApprovalProcessRevokeReq, postWorkflowApprovalProcessRevoke } from '@/api';
import { ILoadingCallback } from '@/components/base/Dialog';
import { Teleport } from 'vue';
import emitter from '@numa/common/utils/emitter';

type TSubmitType = 'complete' | 'comment';

/**
 * 填写撤回原因
 */
const RevokeDialog = defineComponent({
  setup() {
    const { processInstanceId } = useApprovalProvide();
    const formRef = ref<IVitalFormV2Ctx<IPostWorkflowApprovalProcessRevokeReq>>();
    const formConfig = createFormV2<IPostWorkflowApprovalProcessRevokeReq>({
      attrs: {},
      mode: 'edit',
      formItems: [
        {
          attrs: {
            label: ''
          },
          fields: [
            {
              type: 'richEditor',
              prop: 'reason',
              attrs: {
                placeholder: i18n.t('请输入撤回原因')
              }
            }
          ]
        }
      ]
    });

    const handleSubmit = async (loadingCallback?: ILoadingCallback) => {
      const { validate, getModel } = formRef.value || {};
      await validate?.();
      const model = getModel?.();

      loadingCallback?.(true);

      await postWorkflowApprovalProcessRevoke({
        processInstanceId: processInstanceId.value,
        reason: model?.reason || ''
      }).finally(() => {
        loadingCallback?.(false);
      });
      emitter.emit(approvalRefreshEventName);
      MciNotification.success(i18n.t('撤回成功'));
    };
    return {
      formConfig,
      formRef,
      handleSubmit
    };
  },
  render() {
    return (
      <MciDialog title={i18n.t('原因')} width="784px" confirmHandle={this.handleSubmit}>
        <VitalFormV2 ref="formRef" config={this.formConfig} />
      </MciDialog>
    );
  }
});

export const ApprovalFooter = defineComponent({
  props: {
    drawerVisible: {
      type: Boolean,
      default: false
    }
  },
  setup() {
    const { approvalMode, isSubmitUser, isApprovalUser } = useApprovalProvide();
    const { isRevokeMode } = useRevoke();

    const revokeDialogVisible = ref(false);

    // 审批意见 | 审批评论
    const submitType = ref<TSubmitType>('complete');
    const commentRef = ref(null as TNullable<InstanceType<typeof ApprovalCommentForm>>);

    const changeSubmitType = (type: TSubmitType) => {
      submitType.value = type;
    };
    // 回复
    const handleReply = (user: any) => {
      changeSubmitType('comment');
      commentRef.value?.setReply(user);
    };
    const maxEditorHeight = ref();
    const setHeight = () => {
      maxEditorHeight.value = (window.innerHeight - 200) * 0.45 + 'px';
    };

    const handleRevoke = () => {
      revokeDialogVisible.value = true;
    };

    onMounted(() => {
      setHeight();
      document.addEventListener('resize', setHeight);
    });
    onUnmounted(() => {
      document.removeEventListener('resize', setHeight);
    });

    return {
      approvalMode,
      submitType,
      maxEditorHeight,
      isRevokeMode,
      isSubmitUser,
      isApprovalUser,
      revokeDialogVisible,
      commentRef,
      handleRevoke,
      handleReply,
      changeSubmitType
    };
  },
  render() {
    // 审批操作
    if (this.approvalMode === 'edit') {
      return (
        <div class="approval-footer">
          <ApprovalComplete
            vShow={this.submitType === 'complete'}
            class="mt-16px"
            isFull={this.drawerVisible}
            maxEditorHeight={this.maxEditorHeight}
            onComment={() => this.changeSubmitType('comment')}
          />
          <ApprovalCommentForm
            vShow={this.submitType === 'comment'}
            ref="commentRef"
            maxEditorHeight={this.maxEditorHeight}
            onCancel={() => this.changeSubmitType('complete')}
          />
        </div>
      );
    }

    // 评论操作
    if (this.isSubmitUser || this.isApprovalUser) {
      return (
        <div class="approval-footer">
          <div vShow={this.submitType === 'complete'} class="pt-16 flex">
            {/*  撤回操作  */}
            {this.isRevokeMode ? (
              <MciButton type="info" link onClick={this.handleRevoke}>
                <span class="mci-icon-undo mr-2"></span>
                {i18n.t('撤回')}
              </MciButton>
            ) : null}

            <MciButton type="info" link onClick={() => this.changeSubmitType('comment')} style="margin-left:0 ">
              <span class="mci-icon-add-comment mr-2"></span>
              {i18n.t('评论')}
            </MciButton>
          </div>
          <ApprovalCommentForm
            vShow={this.submitType === 'comment'}
            ref="commentRef"
            maxEditorHeight={this.maxEditorHeight}
            onCancel={() => this.changeSubmitType('complete')}
          />
          <Teleport to="body">
            <RevokeDialog vModel={this.revokeDialogVisible} />
          </Teleport>
        </div>
      );
    }
    return null;
  }
});
